<template>
  <view
    class="home-page"
    :style="{ 'background-image': `url(${home_bg})` }"
  >
    <view
      class="top-wrap"
      :style="{ 'padding-top': `${MBTop}px` }"
    >
      <view
        class="top-title"
        :style="{
          height: `${MBHeight}px`,
          'line-height': `${MBHeight}px`,
          'margin-bottom': '18rpx'
        }"
      >
        习惯百日行
      </view>
      <scroll-view
        v-show="!mainType"
        class="today-content-wrap"
        :scroll-y="true"
        :refresher-enabled="true"
        refresher-default-style="none"
        refresher-background="none"
        :refresher-triggered="refresherTriggered"
        @refresherRefresh="refresherRefresh"
      >
        <view class="list-content">
          <border-box
            class="border-box-use"
            :inside-padding="16"
          >
            <view
              class="top-item"
              :style="{ 'background-image': `url(${today_libai})` }"
            >
              <view class="time-title">
                {{ todayInfo.date }}
              </view>
              <view class="week">
                {{ todayInfo.week }}
              </view>
              <view class="desc">
                {{ todayInfo.tips }}
              </view>
              <view
                v-if="todayInfo.clock_log && todayInfo.clock_log.length"
                class="check-in"
                :class="{ 'check-in-todo': todayInfo.no_clock_num > 0 }"
                :style="{
                  'background-image': `url(${
                    todayInfo.no_clock_num > 0 ? today_pen : ''
                  })`
                }"
              >
                {{ todayCheckTips }}
              </view>
            </view>
          </border-box>
          <view v-if="todayInfo.clock_log && todayInfo.clock_log.length">
            <border-box
              v-for="n in todayInfo.clock_log"
              :key="n.id"
              :inside-padding="16"
              class="border-box-use"
            >
              <view class="list-item">
                <view class="item-left">
                  <view class="time">
                    {{ n | formateTime }}
                  </view>
                  <view class="desc">
                    活动：{{ n.activity_title }}
                  </view>
                  <view class="theme">
                    主题：{{ n.theme_title }}
                  </view>
                </view>
                <view class="item-right">
                  <view
                    v-if="n.son_status === COUNTDOWN"
                    class="btn"
                    :class="{ dis: n.son_status === ALREADY_CLOCKED }"
                    :style="{ 'background-image': `url(${today_btn})` }"
                    @tap="clockIn(n.id)"
                  >
                    {{ `倒计时${n.left_days}天` }}
                  </view>
                  <view
                    v-else
                    class="btn"
                    :class="{ dis: n.son_status === ALREADY_CLOCKED }"
                    :style="{ 'background-image': `url(${today_btn})` }"
                    @tap="clockIn(n.id)"
                  >
                    {{ n.son_status | formateButtonDesc }}
                  </view>
                </view>
              </view>
            </border-box>
          </view>
          <view v-else>
            <view
              class="today-empty"
              :style="{ 'background-image': `url(${defaultPageInfo.bgImage})` }"
            >
              {{ defaultPageInfo.word }}
            </view>
            <view
              class="today-empty-btn"
              :style="{ 'background-image': `url(${today_btn2})` }"
              @tap="toRecommend"
            >
              {{ defaultPageInfo.btnWord }}
            </view>
          </view>
        </view>
      </scroll-view>
      <contactTeacher ref="contactTeacher" v-if="mainType"  />
      <AwardGive :show.sync="showAward" :position="'index'" />
    </view>
  </view>
</template>

<script>
import {
  home_bg,
  today_libai,
  today_pen,
  today_btn,
  today_btn2,
  today_empty,
  DEFAULT_IMAGE
} from "@/libs/image-url";
import { NOT_LOGIN_DEFAULT } from "@/pages/not-login/image-url";
import {
  bannerList,
  hasHabitActivity,
  activityLists,
  todayInfo
} from "_api/home";
import basicDataSet from "@/config/basic-data-set";
import Taro from "@tarojs/taro";
import globalData from "@/libs/globalData";
import borderBox from "_c/border-box/index";
import contactTeacher from "_c/contact-teacher/index";
import avatarGroup from "_c/avatar-group";
// 按需引入, 更小的应用体积
import { AtDivider } from "taro-ui-vue";
import "./index.scss";
import { activity_offline } from "@/libs/image-url";
import AwardGive from "@/components/award-give/index.vue";
import {
  DEFAULT_SHARED_IMAGE
} from '@/config/v-2-3-cdn'

const CHECK_TIPS_TEXT = "棒！你已完成今日所有任务~";
const LIST_SCROLL_OFFSET = 288;
/* 胶囊banner标识 */
const CAPSULE_BANNER_TYPE = 2;

/**打卡状态 */
const TO_CHECK_IN = 1 // 去打卡
const NON_CHECK_IN_TIME = 2 // 非打卡时间段
const COUNTDOWN = 3 // 倒计时打卡
const ALREADY_CLOCKED = 4 // 已打卡

export default {
  components: {
    borderBox,
    contactTeacher,
    avatarGroup,
    AwardGive
  },
  filters: {
    formateButtonDesc: (value) => {
      const map = {
        [TO_CHECK_IN]: '去完成',
        [NON_CHECK_IN_TIME]: '非活动时段',
        [ALREADY_CLOCKED]: '已完成',
      }
      return map[value]
    },
    /**格式化时间显示 */
    formateTime: (value) => {
      const { clock_start_time, clock_end_time, son_status, clock_time} = value
      if(son_status === ALREADY_CLOCKED){
        const startTime = clock_start_time ? clock_start_time.replace(/(\d{2}:\d{2}):\d{2}/g, '$1') : ''
        const endTime = clock_end_time ? clock_end_time.replace(/(\d{2}:\d{2}):\d{2}/g, '$1') : ''
        return `${startTime}-${endTime}`
      }
      return son_status === COUNTDOWN ?'即将开启' : son_status === NON_CHECK_IN_TIME ? `${clock_time} 开启活动` : clock_time
    }
  },
  data() {
    return {
      home_bg,
      today_libai,
      today_pen,
      today_btn,
      today_btn2,
      today_empty,
      activity_offline,
      MBTop: 0,
      MBHeight: 0,
      mainType: 0,
      activity_type: 1,
      show: false,
      isOpened: false,
      mainWrapCanScroll: true,
      listCanScroll: false,
      swiperShow: true,
      query: {
        city_id: "",
        grade_id: ""
      },
      isEnd: false,
      bannerList: [],
      hasHabitActivity: 0,
      activityLists: [],
      page: 1,
      refresherTriggered: false,
      todayInfo: {
        clock_log: []
      },
      todayCheckTips: CHECK_TIPS_TEXT,
      today: 0,
      showAward: false,
      showBlock: false,
      offsetHeight: "",
      /* 胶囊banner */
      capsuleBanner: [],
      /**是否已登录 */
      isLogin: false,
      /**打卡状态 */
      TO_CHECK_IN,
      NON_CHECK_IN_TIME,
      COUNTDOWN,
      ALREADY_CLOCKED
    };
  },
  computed: {
    /**标题距离顶部的高度 */
    titleToTopDistanceStyle() {
      /**
       * 18rpx为top-title元素的marginBottom
       * 125rpx为main-tabs元素的整体高度
       *
       */
      return {
        height: `calc(100% - ${this.MBTop + this.MBHeight}px - 18rpx - 125rpx)`,
        width: "100%"
      };
    },
    /**缺省页信息-登录和未登录 */
    defaultPageInfo() {
      const bgImage = this.isLogin ? today_empty : NOT_LOGIN_DEFAULT;
      const word = this.isLogin
        ? "你还没有参与活动哦，去首页看看吧～"
        : "登录后即可参与活动哦~";
      const btnWord = this.isLogin ? "去看看" : "去登录";
      return { bgImage, word, btnWord };
    },
  },
  async onLoad(opt) {
    this.query = {
      city_id: Taro.getStorageSync("city_id"),
      grade_id: Taro.getStorageSync("grade_id")
    };
    this.MBHeight = globalData.getData("MBHeight");
    this.MBTop = globalData.getData("MBTop");
    console.log(this.titleToTopDistance);
  },
  async onShow() {
    this.getTodayInfo();
    /**重新获取联系老师 */
    this.$refs.contactTeacher && this.$refs.contactTeacher.getInfo()
  },

  onShareAppMessage() {
    return {
      title: "参加习惯百日行，与百万伙伴同行，更有大奖等你来领！",
      path: "/pages/index/index?register_channel=mini_program",
      imageUrl: DEFAULT_SHARED_IMAGE,
    };
  },
  methods: {
    /* 去推荐页面 */
    toRecommend() {
      if (this.isLogin) {
        Taro.switchTab({
          url: "/pages/index/index"
        });
        return;
      }
      Taro.navigateTo({
        url: "/pages/not-login/index"
      });
    },
    scrollList({ detail: { scrollTop } }) {
      if (scrollTop > 50) {
        this.swiperShow = false;
      } else {
        this.swiperShow = true;
      }
    },
    scrollToLowerList(e) {
      if (this.isEnd) {
        return;
      }
      this.getActivityLists(this.page);
    },
    async refresherRefresh() {
      this.refresherTriggered = true;
      this.mainType && (await this.getActivityLists(1, true));
      !this.mainType && (await this.getTodayInfo());
      this.refresherTriggered = false;
    },
    handleMainType(type) {
      this.mainType = type;
      this.mainType && this.getActivityLists(1, true);
      !this.mainType && this.getTodayInfo();
    },
    getTodayInfo() {
      return todayInfo().then(({ data }) => {
        const { date, tips, week, is_login = true } = data;
        this.isLogin = is_login

        this.todayInfo = this.isLogin ? data.data : { date, tips, week };

        // this.todayInfo.clock_log = []
        this.todayCheckTips =
          this.todayInfo.no_clock_num > 0
            ? `今日还有${
                this.todayInfo.no_clock_num > 999
                  ? "999+"
                  : this.todayInfo.no_clock_num
              }项未完成哦`
            : CHECK_TIPS_TEXT;
      });
    },
    handleSubType(type) {
      this.activity_type = type;
      // console.log(this.$refs.listScroll)
      this.getActivityLists(1, true);
    },
    goAvtivityDetail(id) {
      console.log(id);
      Taro.navigateTo({
        url: `/package/activity-detail/index?id=${id}`
      });
    },
    clockIn(id) {
      /* Taro.setStorageSync("comeFromToday", 1); */
      Taro.navigateTo({
        url: `/package/theme-detail/index?id=${id}`
      });
    }
  }
};
</script>
